//
//  calenderView.m
//  CalenderDemo
//
//  Created by GZMLUser on 14-11-6.
//  Copyright (c) 2014年 GZMLUser. All rights reserved.
//

#import "calenderView.h"
#import "DateDay.h"


#define DateLabelHeigth 30
#define WeekDayLabelHeigth 25
#define PopCalendarRect CGRectMake(20, 150, 280, 200) // 在中间显示大小
// 在下边显示大小
#define BottomCalendarRect CGRectMake(0, CGRectGetHeight(self.superView.bounds) - 250, CGRectGetWidth(self.superView.bounds), 250)
// 日期被选择背景颜色
#define selectedBackgroundColor [UIColor colorWithRed:125/255.0 green:208/255.0 blue:0/255.0 alpha:1.0]
#define currentDateColor [UIColor colorWithRed:242/255.0 green:121/255.0 blue:53/255.0 alpha:1.0]  // 当前日期字体颜色

#define SET_FRAME(ARTICLEX) y = ARTICLEX.frame.origin.y + increase;\
if(y < 0) y = _calendarViewHeigth * 4;\
if(y > _calendarViewHeigth * 4) y = 0.0f;\
[ARTICLEX setFrame:CGRectMake(ARTICLEX.frame.origin.x, y,ARTICLEX.frame.size.width,ARTICLEX.frame.size.height)]  // 设置三个pageView位置

@implementation calenderView 
@synthesize currentDate = _currentDate;
- (id)initWithAnimateTye:(Type)animateType andDate:(NSDate *)date addToSuperView:(UIView *)superView
{
    self = [super init];
    if (self) {
        // 初始化
        self.backgroundColor = [UIColor clearColor];
        _calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        self.currentDate = date;
        _type = animateType;
        
        preIndex = -2;
        
        nexIndex  = 2;

        _superView = superView;
        self.frame = _superView.bounds;
        [self initCalender];
        
        // 添加手势收回日历
        UIPanGestureRecognizer *panGresture = [[UIPanGestureRecognizer alloc]initWithTarget: self action:@selector(panGesturehandle:)];
        [panGresture setMinimumNumberOfTouches:1];
        [panGresture setMaximumNumberOfTouches:1];
        [self addGestureRecognizer:panGresture];
        [self setUserInteractionEnabled:YES];
        
    }
    return self;
}

#pragma mark - 手势处理
- (void)panGesturehandle:(UIPanGestureRecognizer *)recongnizer
{
//    CGPoint translatedPoint = [recongnizer translationInView:self];
//    CGFloat y = translatedPoint.y;

}
#pragma mark -setDate方法
//- (void)setCurrentDate:(NSDate *)currentDate // 接受外部date值
//{
//    _currentDate = currentDate;
//    _dateNoTime = !currentDate ? nil : [self dateWithOutTime:currentDate];
//    self.internalDate = [_dateNoTime dateByAddingTimeInterval:0];
//  
//}

- (NSDate *)currentDate
{
    return [self setRigthDate];
}
//- (void)setInternalDate:(NSDate *)internalDate // 设置内部选中时间
//{
//    _internalDate = internalDate;
//    if (_internalDate) {
//        [self setDisplayedMonthFromDate:_internalDate]; // 初始当前时间内相关属性
//    } else {
//        [self.currentDay setSelected:NO];
//        self.currentDay = nil;
//    }
//  
//}

#pragma mark date初始
- (BOOL)dateInCurrentMonth:(NSDate *)date{ // 判断date是否在当前月
    
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [_calendar components:unitFlags fromDate:self.firstOfCurrentMonth];
    NSDateComponents* comp2 = [_calendar components:unitFlags fromDate:date];
    return [comp1 year]  == [comp2 year] && [comp1 month] == [comp2 month];
}

- (NSDate *)dateWithOutTime:(NSDate *)datDate {
    if( datDate == nil ) {
        datDate = [NSDate date];
    }
    NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:datDate];
    return [[NSCalendar currentCalendar] dateFromComponents:comps];
}



#pragma mark -设置日历每月显示
- (void)setDisplayedMonthFromDate:(NSDate *)date{
    NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date];
    [self setDisplayedMonth:(int)[comps month] year:(int)[comps year]];
}

- (void)setDisplayedMonth:(int)month year:(int)year{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM"];
    self.firstOfCurrentMonth = [df dateFromString: [NSString stringWithFormat:@"%d-%@%d", year, (month<10?@"0":@""), month]];
    [self storeDateInformation];
}
// 计算每月相关数值
- (void)storeDateInformation{
    NSDateComponents *comps = [_calendar components:NSWeekdayCalendarUnit | NSDayCalendarUnit fromDate:self.firstOfCurrentMonth];
    NSCalendar *c = [NSCalendar currentCalendar];
#ifdef DEBUG
    [c setFirstWeekday:2]; // 从星期一开始
#endif
    NSRange days = [c rangeOfUnit:NSDayCalendarUnit
                           inUnit:NSMonthCalendarUnit
                          forDate:self.firstOfCurrentMonth];
    // 距离星期相差数
    int bufferDaysBeginning = (int)([comps weekday]-[c firstWeekday]);
    
    if (bufferDaysBeginning < 0)
        bufferDaysBeginning += 7;
    int daysInMonthWithBuffer = (int)(days.length + bufferDaysBeginning);
    int numberOfWeeks = daysInMonthWithBuffer / 7;
    if(daysInMonthWithBuffer % 7) numberOfWeeks++;
    
    _weeksOnCalendar = 6;
    _bufferDaysBeginning = bufferDaysBeginning;
    _daysInMonth = (int)days.length;
    
}


#pragma mark 绘制日历
- (void)initCalender
{
    // 通过frame初始视图
    
    self.calendarView = [[UIView alloc]init]; // 初始日历View
    
    // 通过类型设置日历大小
    CGRect calendarRect;
    if (_type == Popping) { // 中间显示
        calendarRect = PopCalendarRect;
        
    } else {
        calendarRect = BottomCalendarRect;
    }
    self.calendarView.frame = calendarRect;
    // 根据当前日期设置相关属性
    if (!self.firstOfCurrentMonth) {
        [self setDisplayedMonthFromDate:[NSDate date]];
    }
  
    // 设置日历View
    [self drawCalendarViewWithFrame:self.calendarView.bounds];

}

- (void)drawCalendarViewWithFrame:(CGRect)rootRect
{
 
    /************** 设置日历表格视图 及星期label**********/
    
    // 添加两个对日历监听按钮
   CGRect buttonRect = CGRectMake(rootRect.origin.x, rootRect.origin.y, CGRectGetWidth(rootRect), WeekDayLabelHeigth);
    UIView *buttonView = [self setButtonInViewWithRect:buttonRect];
    [self.calendarView addSubview:buttonView];
    // 日期显示
    CGRect showLabelRect = CGRectMake(rootRect.origin.x, CGRectGetMaxY(buttonView.bounds), CGRectGetWidth(rootRect), WeekDayLabelHeigth );
    UILabel *datesLabel = [self setShowDateLabelWithRect:showLabelRect];
    
    [self.calendarView addSubview:datesLabel];
    // 星期label
    CGRect weekLabelRect = CGRectMake(rootRect.origin.x, CGRectGetMaxY(showLabelRect), CGRectGetWidth(rootRect), WeekDayLabelHeigth);
    UIView *weekLabelView = [self setWeekdaysLabelWithSize:weekLabelRect];
    [self.calendarView addSubview:weekLabelView];
    // 日历
    CGRect calendarRect = CGRectMake(0, CGRectGetMaxY(weekLabelRect), CGRectGetWidth(rootRect), CGRectGetHeight(rootRect) - CGRectGetMaxY(weekLabelRect));
    _calendarViewHeigth = CGRectGetHeight(rootRect) - CGRectGetMaxY(weekLabelRect);// 日历高度
    UIScrollView *calendardaysListScrorllView = [self setScrollViewWithRect:calendarRect];
    [self.calendarView addSubview:calendardaysListScrorllView];
    
    [self addSubview:self.calendarView];
    [self bringSubviewToFront:self.calendarView];
    
    [self showCalendarView]; // 动画显示
}

#pragma mark -动画显示日历控件
- (void)showCalendarView
{
    if (self.type == Popping) {
        self.calendarView.transform = CGAffineTransformMakeScale(0.007, 0.007);
        //开始动画
        [UIView animateWithDuration:0.5f animations:^{
            
            self.calendarView.transform = CGAffineTransformMakeScale(1.05, 1.05);
        }completion:^(BOOL finish){
            [UIView animateWithDuration:0.2f animations:^{
                self.calendarView.transform = CGAffineTransformMakeScale(1,1);
            }completion:^(BOOL finish){
                [UIView animateWithDuration:0.2f animations:^{
                    self.calendarView.transform = CGAffineTransformMakeScale(1,1);
                }completion:^(BOOL finish){
                    //调用完成动画块
                                 }];
            }];
        }];

    } else {
        // 设置到最底部
        self.calendarView.frame = CGRectMake(0, CGRectGetMaxY(self.bounds), CGRectGetWidth(self.calendarView.bounds), CGRectGetHeight(self.calendarView.bounds));
        [UIView animateWithDuration:0.5f animations:^{
            self.calendarView.frame = CGRectMake(0, CGRectGetMaxY(self.bounds) - CGRectGetHeight(self.calendarView.bounds), CGRectGetWidth(self.calendarView.bounds),CGRectGetHeight(self.calendarView.bounds));
        } completion:nil];
    
    }
}
- (void)removeTheCalendarView // 移除日历
{
    if (self.type == Popping) {
        [UIView animateWithDuration:.5f animations:^{
            self.calendarView.transform = CGAffineTransformMakeScale(0.007, 0.007);
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    } else {
        [UIView animateWithDuration:.5f animations:^{
            self.calendarView.frame = CGRectMake(0, CGRectGetMaxY(self.bounds), CGRectGetWidth(self.calendarView.bounds), CGRectGetHeight(self.calendarView.bounds));
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
        
    }
}

#pragma mark - bttonView
- (UIView *)setButtonInViewWithRect:(CGRect)buttonRect
{
    UIView *buttonView = [[UIView alloc]initWithFrame:buttonRect];
    buttonView.backgroundColor = [UIColor whiteColor];
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    deleteButton.frame = CGRectMake(10, 0, 40, 25);
    [deleteButton setImage:[UIImage imageNamed:@"dialog_cancel.png"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:deleteButton];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
    sureButton.frame = CGRectMake(CGRectGetWidth(buttonView.bounds) - 40 - 10, 0,40, 25);
    [sureButton setImage:[UIImage imageNamed:@"dialog_ok.png"] forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(sureButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:sureButton];
    
    return buttonView;
}

#pragma mark -日期显示
- (UILabel *)setShowDateLabelWithRect:(CGRect)showLabelRect
{
    NSString *mothName = [self stringFromDate:self.firstOfCurrentMonth];
    UILabel *showLabel = [[UILabel alloc]initWithFrame:showLabelRect];
    showLabel.backgroundColor = [UIColor whiteColor];
    showLabel.text = mothName;
    showLabel.font = [UIFont systemFontOfSize:17.0f];
    showLabel.textAlignment = NSTextAlignmentCenter;
    self.monthLabel = showLabel;
    return self.monthLabel;
}
- (NSString *)stringFromDate:(NSDate *)date // 根据date的到月份字符串
{
    NSString *dateString = nil;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MMMM yyyy"];
    NSString *mothName = [formatter stringFromDate:date];
    
    dateString = mothName;
    return dateString;
}

#pragma mark -绘制日历
- (UIView *)setCalendarViewWithRect:(CGRect)calendarRect
{
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:-_bufferDaysBeginning];
    NSDate * date = [_calendar dateByAddingComponents:offsetComponents toDate:self.firstOfCurrentMonth options:0];
    [offsetComponents setDay:1];
    // 日历表格
    CGRect calerRect = calendarRect;

    self.calendarDaysView  = [[UIView alloc]initWithFrame:calerRect];

    UIView * container = _calendarDaysView;
    CGRect containerFrame = container.frame;
    int areaWidth = containerFrame.size.width;
    int areaHeight = containerFrame.size.height;
    int cellWidth = areaWidth/7;
    int cellHeight = areaHeight/_weeksOnCalendar;
    int days = _weeksOnCalendar*7;
    int curY = (areaHeight - cellHeight*_weeksOnCalendar)/2;
    int origX = (areaWidth - cellWidth*7) / 2;
    int curX = origX;
    
    // 设置日历表格
    for(int i = 0; i < days; i++){
        if(i && !(i%7)) {
            curX = origX;
            curY += cellHeight;
        }
        
        DateDay * day = [[[NSBundle mainBundle] loadNibNamed:@"DateDay" owner:self options:nil] objectAtIndex:0];
        // 设置当前日期选中及背景颜色
        [day setCurrentDateColor:currentDateColor];
        [day setSelectedBackgroundColor:selectedBackgroundColor];
        
        day.frame = CGRectMake(curX, curY, cellWidth, cellHeight);
        
        day.delegate = self; // 设置点击代理
        
        day.date = [date dateByAddingTimeInterval:0];
        
        // 当前日期设置
//        if(_internalDate && ![date timeIntervalSinceDate:_internalDate]) {
//            [day setSelected:YES];
//            self.currentDay = day; // 当前选中日期
//        }
        if ([self isToday:date]) {
            [day setSelected:YES];
            self.currentDay = day;
        }
        NSDateComponents *comps = [_calendar components:NSDayCalendarUnit fromDate:date];
        // 更改button日期文字
        [day.dateButton setTitle:[NSString stringWithFormat:@"%ld",(long)[comps day]]
                        forState:UIControlStateNormal];
        // 区分当月日期颜色
        [day setLightText:![self dateInCurrentMonth:date]];
        
        [self.calendarDaysView addSubview:day];
        
        date = [_calendar dateByAddingComponents:offsetComponents toDate:date options:0];
        curX += cellWidth;
    }
    
    return self.calendarDaysView;
}

- (BOOL)isToday:(NSDate *)date
{
    NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
    NSDateComponents *today = [[NSCalendar currentCalendar] components:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
    return ([today day] == [otherDay day] &&
            [today month] == [otherDay month] &&
            [today year] == [otherDay year] &&
            [today era] == [otherDay era]);
}
#pragma mark -绘制星期Label
- (UIView *)setWeekdaysLabelWithSize:(CGRect)weekLabelRect
{
    self.weekDayView = [[UIView alloc]initWithFrame:weekLabelRect];
    self.weekDayView.backgroundColor = [UIColor whiteColor];
    CGSize fullSize = weekLabelRect.size;
    int dayWidth = fullSize.width / 7;
    int curX = (fullSize.width - 7*dayWidth)/2;
    NSDateComponents * comps = [_calendar components:NSDayCalendarUnit fromDate:[NSDate date]];
    NSCalendar *c = [NSCalendar currentCalendar];
#ifdef DEBUG
    [c setFirstWeekday:2];
#endif
    [comps setDay:[c firstWeekday]-1];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:1];
    [df setDateFormat:@"EE"];
    NSDate * date = [_calendar dateFromComponents:comps];
    for(int i = 0; i < 7; i++){
        UILabel * dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(curX, 0, dayWidth, fullSize.height)];
        dayLabel.textAlignment = NSTextAlignmentCenter;
        dayLabel.font = [UIFont systemFontOfSize:12];
        
        [self addSubview:dayLabel];
        dayLabel.text = [df stringFromDate:date];
        dayLabel.textColor = [UIColor grayColor];
        date = [_calendar dateByAddingComponents:offsetComponents toDate:date options:0];
        curX+=dayWidth;
        
        // 添加label
        [self.weekDayView addSubview:dayLabel];
    }
    return self.weekDayView;
}


#pragma mark -scrollView设置
- (UIScrollView *)setScrollViewWithRect:(CGRect)scrollViewRect
{
    CGRect contentRect = scrollViewRect;
    // 设置scrollView
    self.scrollView = [[UIScrollView alloc]initWithFrame:contentRect];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.bounces = NO; // 没有反弹效果
    self.scrollView.backgroundColor = [UIColor grayColor];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    // 在垂直方向滚动
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(contentRect), CGRectGetHeight(self.scrollView.bounds) * 5);
    self.scrollView.contentOffset = CGPointMake(0, CGRectGetHeight(contentRect)*2);
    
    // 添加内容
    _preView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(contentRect), CGRectGetHeight(contentRect))];
    [self addSubViewAtMounthIndex:-2  TopageView:_preView];
    _preView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_preView];
    
    _secendPreView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(contentRect), CGRectGetWidth(contentRect), CGRectGetHeight(contentRect))];
    [self addSubViewAtMounthIndex:-1  TopageView:_secendPreView];
    _secendPreView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_secendPreView];

    
    _nextView = [[UIView alloc]initWithFrame:CGRectMake(0, 4 * CGRectGetHeight(contentRect),CGRectGetWidth(contentRect), CGRectGetHeight(contentRect))];
    [self addSubViewAtMounthIndex:2  TopageView:_nextView];
    _nextView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_nextView];
    
    _secendNextView = [[UIView alloc]initWithFrame:CGRectMake(0, 3 * CGRectGetHeight(contentRect),CGRectGetWidth(contentRect), CGRectGetHeight(contentRect))];
    [self addSubViewAtMounthIndex:1  TopageView:_secendNextView];
    _secendNextView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_secendNextView];
    
    // 当前
    _currView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(contentRect)*2, CGRectGetWidth(contentRect), CGRectGetHeight(contentRect))];
    [self addSubViewAtMounthIndex:0  TopageView:_currView];
    _currView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_currView];
    
    return self.scrollView;
}

#pragma mark -添加日历View到pageView上
- (void)addSubViewAtMounthIndex:(int)mounthIndex TopageView:(UIView *)pageView
{
    [self incrementMonth:mounthIndex];
    [pageView addSubview:[self setCalendarViewWithRect:pageView.bounds]];
    
}
- (void)setCalendarLabelAtMonthIndex:(int)index // 重设月份label
{
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setMonth:index];
    NSDate * incrementedMonth = [_calendar dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
    self.monthLabel.text = [self stringFromDate:incrementedMonth];
}
- (void)incrementMonth:(int)incrValue{// 计算月份相距日期
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setMonth:incrValue];
    NSDate * incrementedMonth = [_calendar dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];
    [self setDisplayedMonthFromDate:incrementedMonth];
}

#pragma mark - 重置日历列表
- (void)allArticlesMoveUp:(CGFloat)pageWith // 向上
{
    UIView *tempView = _nextView;
    _nextView = _secendNextView;
    _secendNextView = _currView;
    _currView = _secendPreView;
    _secendPreView = _preView;
    _preView = tempView;
    
    float increase = pageWith / 2;
    CGFloat y = 0.0f;
    SET_FRAME(_nextView);
    SET_FRAME(_preView);
    SET_FRAME(_currView);
    SET_FRAME(_secendPreView);
    SET_FRAME(_secendNextView);
    
    // 改变移动位置的View上的内容
    if (_preView) {
        for (UIView *sub in _preView.subviews) {
            [sub removeFromSuperview];
        }
        [self addSubViewAtMounthIndex:--preIndex TopageView:_preView];
        --nexIndex;
        [self setCalendarLabelAtMonthIndex:preIndex + 2]; // 设置月份显示
    }
    
}
- (void)allArticlesMoveDown:(CGFloat)pageWidth { // 向下
    UIView *tmpView = _preView;
    _preView = _secendPreView;
    _secendPreView = _currView;
    _currView = _secendNextView;
    _secendNextView = _nextView;
    _nextView = tmpView;
    
    float increase = -pageWidth / 2;
    CGFloat y = 0.0f;
    SET_FRAME(_currView);
    SET_FRAME(_nextView);
    SET_FRAME(_preView);
    SET_FRAME(_secendNextView);
    SET_FRAME(_secendPreView);
    if (_nextView) {
        for (UIView *sub in _nextView.subviews) {
            [sub removeFromSuperview];
        }
        [self addSubViewAtMounthIndex:++nexIndex TopageView:_nextView];
        ++preIndex;
        // 关联月份
        [self setCalendarLabelAtMonthIndex:nexIndex - 2];
    }
    
}

#pragma mark -按钮监听
- (void)deleteButtonClicked
{
    [self removeTheCalendarView];
    
}
- (void)sureButtonClicked
{
    [self removeTheCalendarView];
    if ([self.delegate respondsToSelector:@selector(calendarViewDoneClicked:)]&&self.currentDate) {
        [self.delegate calendarViewDoneClicked:self];
    }
}
#pragma mark -日期点击代理
-(void)dateDayTapped:(DateDay *)dateDay
{
    // 移除日历
   // [self removeTheCalendarView];
    
    [self.currentDay setSelected:NO]; // 当前日期
    [dateDay setSelected:YES]; // 选中日期
    self.internalDate = dateDay.date;
    self.currentDay = dateDay;

    if ([self.delegate respondsToSelector:@selector(calendarDayClicked:)]) {
        [self.delegate calendarDayClicked:[self setRigthDate]];
    }
}
- (NSDate *)setRigthDate // 设置成正确时间
{
    int ymd = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSDateComponents* internalComps = [_calendar components:ymd fromDate:self.internalDate];
    int time = NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit;
    NSDateComponents* origComps = [_calendar components:time fromDate:_currentDate];
    [origComps setDay:[internalComps day]];
    [origComps setMonth:[internalComps month]];
    [origComps setYear:[internalComps year]];
    return [_calendar dateFromComponents:origComps];
}

#pragma mark UIScrollView代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)theScrollView
{
    CGFloat pageWidth = _calendarViewHeigth *2;
//    int page = floor((theScrollView.contentOffset.y - pageWidth / 2) / pageWidth) + 1;
//    if(page == 1) {
//        //用户拖动了，但是滚动事件没有生效
//        return;
//        
//    } else if (page == 0) {
//        [self allArticlesMoveUp:pageWidth];
//    } else {
//        [self allArticlesMoveDown:pageWidth];
//    }
//    
    CGPoint p = CGPointZero;
    p.y = pageWidth;
    
    
    
    if ([theScrollView contentOffset].y > pageWidth) {
        [self allArticlesMoveDown:pageWidth];
    } else if ([theScrollView contentOffset].y < pageWidth) {
        [self allArticlesMoveUp:pageWidth];
    }
    [theScrollView setContentOffset:p animated:NO];
}


#pragma mark -给pop类型日历添加边
- (void)drawRect:(CGRect)rect
{
    if (self.type == Popping) {
        [self.calendarView.layer setCornerRadius:5.0f];
        [self.calendarView.layer setMasksToBounds:YES];
        
        [self.calendarView.layer setBorderWidth:2.0f];
        [self.calendarView.layer setBorderColor:[UIColor grayColor].CGColor];
    }
    
}



@end
